<?php
namespace App\System\Http;

use App\System\Http\Message\Response as MessageResponse;
use App\System\Http\Message\Status;
use App\System\Http\Message\Utility;

class Response extends MessageResponse
{

    private $isEndResponse = false;

    final public function __construct()
    {
        parent::__construct();
    }

    function response(): bool
    {
        $this->isEndResponse = true;
        // 结束处理
        $status = $this->getStatusCode();
        $headers = $this->getHeaders();
        
        if (! headers_sent() && ! empty($headers)) {
            // 发送状态码
            http_response_code($status);
            // 发送头部信息
            foreach ($headers as $header => $val) {
                foreach ($val as $sub) {
                    header($header . ':' . $sub);
                }
            }
        }
        // 处理cookie
        $cookies = $this->getCookies();
        if ($cookies) {
            foreach ($cookies as $cookie) {
                setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpire(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
            }
        }
        
        $write = $this->getBody()->__toString();
        if (! empty($write)) {
            echo $write;
        }
        $this->getBody()->close();
        exit();
        return true;
    }

    function write(string $str)
    {
        $this->getBody()->write($str);
    }

    final public function __toString(): string
    {
        // TODO: Implement __toString() method.
        return Utility::toString($this);
    }

    function setIsEndResponse($is)
    {
        $this->isEndResponse = $is;
    }

    function isEndResponse(): bool
    {
        return $this->isEndResponse;
    }
}